package com.dao;

import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.xml.crypto.dsig.DigestMethod;

import com.entity.Filer;
import com.entity.User;
import com.util.DBHelp;
import com.util.RowMapper;

public class FilerDao {

	private DBHelp<Filer> db=new DBHelp<Filer>();
	
	
	public List<Filer> list(String folderid){
		String sql = "select tf.id,tf.filename,tf.changename,tf.folderid,tf.kind,tf.size,tf.createtime,tf.userid,tu.username,tu.image from t_filer AS tf left join t_user AS tu on tu.id=tf.userid  where tf.folderid=?";
		return db.executeQueryForList(sql, new FilerRowMapper(),folderid);
	}
	
	public  long count(String folderid){
		String sql="select count(id) from t_filer  where folderid = ?";
		return (Long) db.executeQueryForFunction(sql, folderid);
	}
	
	public String sumSize(String folderid){
	  	String  sql="select sum(size) from t_filer where folderid = ?";
		BigDecimal result=(BigDecimal) db.executeQueryForFunction(sql,folderid);
		
		return result.toString();
	}
	
	private class FilerRowMapper implements RowMapper<Filer> {

		public Filer mapRow(ResultSet rs) throws SQLException {
			Filer f=new Filer();
			
			f.setChangeName(rs.getString("changename"));
			f.setFolderid(rs.getString("folderid"));
			f.setId(rs.getString("id"));
			f.setKind(rs.getString("kind"));
			f.setCreatetime(rs.getString("createtime"));
			f.setSize(rs.getFloat("size"));
			f.setFileName(rs.getString("filename"));

			User u=new User();
			u.setId(rs.getString("userid"));
			u.setImage(rs.getString("image"));
			u.setUserName(rs.getString("username"));
			
			f.setUser(u);
			f.setUserid(rs.getString("userid"));
			return f;
		}
		
	}

	public void save(Filer doc){
		// TODO Auto-generated method stub
		String sql = "INSERT INTO t_filer(id,filename,folderid,createtime,kind,size,changename,userid) values(?,?,?,?,?,?,?,?)";
		db.executeSQL(sql,doc.getId(),doc.getFileName(),doc.getFolderid(),doc.getCreatetime(),doc.getKind(),doc.getSize(),doc.getChangeName(),doc.getUserid());
	}
	
}
